//
//  BalanceModel.m
//  Balance
//
//  Created by Calvin Kuo on 12-03-26.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

/*
 Status: changed
 Last Merge Date: 05-29-2012
 Last Change Date: 
 Changes:
 1. 
 */




#import "BalanceModel.h"
#import <stdlib.h>


@implementation BalanceModel

@synthesize dailyBalances = _dailyBalances;
@synthesize yearlyBalances = _yearlyBalances;
@synthesize agingBucketLabels = _agingBucketLabels;
@synthesize countryBalances = _countryBalances;
@synthesize countryArray = _countryArray;
@synthesize agingBucketLabelsNoCurrentAmount = _agingBucketLabelsNoCurrentAmount;


-(id) init
{
    if (self = [super init])
    {
        //Set up 3 years of data from today back
        NSDateFormatter *df = [[NSDateFormatter alloc]init];  
        [df setDateFormat:@"MMddyyyy"];  
        
        NSDate * newYearDay2012 = [df dateFromString:@"01012012"];
        NSDate * today = [NSDate date];
        NSString *todayString = [df stringFromDate:today];
        NSString *startDateString = [[todayString substringToIndex:4] stringByAppendingString:@"2009"];
        NSDate *startDate = [df dateFromString:startDateString];
        NSDate *endOfYear2009=[df dateFromString:@"12312009"];
        
        NSUInteger daysin2012 = [self getNumberOfDaysFrom:newYearDay2012 to:today] +1;
        NSUInteger daysin2009 = [self getNumberOfDaysFrom:startDate to:endOfYear2009] +1;
                
        numberOfDailyBalances = daysin2009 + 365 + 365 + daysin2012;
               
        Balance *balance = [[Balance alloc]init];
               
        _dailyBalances =
        [NSMutableDictionary dictionaryWithCapacity:2000];
         
        NSTimeInterval oneDay = 24 * 60 * 60;
        
        //***************************************************************************
        //generate data for dailiy balances of 2009-2012; 3 years
        int balAmt, undueAmt,b1Amt, b2Amt, b3Amt, c1Amt, c2Amt;
        int aRand, bRand, cRand, dRand, eRand;
        for (int d=0; d < numberOfDailyBalances; d++) 
        {  
            
            //NSDate *balDate = [today dateByAddingTimeInterval:(oneDay * -d)]; 
            NSDate *balDate = [startDate dateByAddingTimeInterval:(oneDay * d)]; 
            balance = [[Balance alloc]init];
            balance.balanceDate = balDate;
            //balance.timeIntervalSinceToday = oneDay * d;
            balance.timeIntervalSinceToday = oneDay * (numberOfDailyBalances-d-1);
            balance.timeIntervalSinceStart = oneDay * d;
            
            NSDateFormatter *balDateFormatter = [[NSDateFormatter alloc] init];
            [balDateFormatter setDateFormat:@"yyyyMMdd"];
            NSString *balDateString = [balDateFormatter stringFromDate:balDate];
            
            aRand=0;
            bRand=0;
            cRand=0;
            dRand=0;
            eRand=0;
            balAmt=0;
            undueAmt=0;
            b1Amt=0;
            b2Amt=0;
            b3Amt=0;
            c1Amt=0;
            c2Amt=0;
            
            aRand = rand() % 10; //generate a random number
            bRand = rand() % 10; //generate a random number
            cRand = rand() % 10; //generate a random number
            dRand = rand() % 10; //generate a random number
            eRand = rand() % 10; //generate a random number
            //NSLog(@"a=%i,b=%i,c=%i,d=%i,e=%i",aRand,bRand,cRand,dRand,eRand);
            
            //overall balance
            //balAmt= 30000 + 50 *aRand; //all balances = undue+below90+above90 
            // 50 breaks down to  25 + (5+5+5) + 10 for undue, c1 and c2 respectively
            
            int n = 300;
            int t = d-(n*(d/n));
            undueAmt = 40000 + 50*aRand + 40* ((t%n)<(n/2) ? (t%n) : ((t%n)-((t-(n/2))*2))+(d/n)*10);
            
            n = 240;
            t = d-(n*(d/n));
            b1Amt = 1000 + 80 *bRand + 80*((t%n)<(n/2) ? (t%n) : ((t%n)-((t-(n/2))*2))+(d/n)*10);
            //bucket1: 1-30 days
            
            n = 240;
            t = d-(n*(d/n));
            b2Amt = 1000 + 80 *cRand + 80*((t%n)<(n/2) ? (t%n) : ((t%n)-((t-(n/2))*2))+(d/n)*10);; 
            //bucket2: 31-60 days
            
            n = 300;
            t = d-(n*(d/n));
            b3Amt = 500 + 80 *dRand + 80*((t%n)<(n/2) ? (t%n) : ((t%n)-((t-(n/2))*2))+(d/n)*10);; 
            //bucket3: 61-90 days
            
            c1Amt = b1Amt + b2Amt + b3Amt;  //total of below90Days
            
            n = 240;
            t = d-(n*(d/n));
            c2Amt = 500 + 80 *eRand + 80 * ((t%n)<(n/2) ? (t%n) : ((t%n)-((t-(n/2))*2))+(d/n)*10);
            //90+ days
            
            balAmt = undueAmt + c1Amt + c2Amt;
            
            //NSLog(@"balAmt=%i,undueAmt=%i,c1Amt=%i,c2Amt=%i",balAmt,undueAmt,c1Amt,c2Amt);
            
            balance.balanceAmount = [NSNumber numberWithInt:balAmt];
            balance.undueAmount = [NSNumber numberWithInt:undueAmt];
            balance.belowNinetyDaysAmount = [NSNumber numberWithInt:c1Amt];
            balance.bucketOneAmount = [NSNumber numberWithInt:b1Amt];
            balance.bucketTwoAmount = [NSNumber numberWithInt:b2Amt];
            balance.bucketThreeAmount = [NSNumber numberWithInt:b3Amt];
            balance.aboveNinetyDaysAmount = [NSNumber numberWithInt:c2Amt];
            balance.bucketFourAmount = [NSNumber numberWithInt:(0)];
            balance.bucketFiveAmount = [NSNumber numberWithInt:(0)];
            balance.bucketSixAmount = [NSNumber numberWithInt:(0)];
            balance.numberOfOpenInvoices = [NSNumber numberWithInt:bRand];
           
            
            //NSLog(@"bRand=%i,balAmt=%i,undueAmt=%i,b1Amt=%i,b2Amt=%i,b3Amt=%i,c1Amt=%i,c2Amt=%i", bRand,balAmt,undueAmt,b1Amt,b2Amt,b3Amt,c1Amt,c2Amt);
            //NSLog(@"bal model index=%i,key=%@,interval=%f",d,balDateString,balance.timeIntervalSinceStart);
            
            [_dailyBalances setObject:balance forKey: balDateString];
           
        };
       

        
        _agingBucketLabels= [[NSArray alloc] initWithObjects:@"", @"Current",@"1-30", @"31-60", @"61-90", @"91+", nil];
        _agingBucketLabelsNoCurrentAmount= [[NSArray alloc] initWithObjects:@"",@"1-30", @"31-60", @"61-90", @"91+",@"", nil];
        
        //***************************************************************************
        //prepare the country balances
        NSLocale *locale = [NSLocale currentLocale];
        NSArray *countryCodeArray = [NSLocale ISOCountryCodes];
        NSMutableArray *sortedCountryCodeArray = [[NSMutableArray alloc] init];
        for (NSString *code in countryCodeArray) {
            NSString *countryName = [locale displayNameForKey:NSLocaleCountryCode value:code];
            [sortedCountryCodeArray addObject:countryName];
            //NSLog(@"countrcode=%@",code);
        };
        [sortedCountryCodeArray sortUsingSelector:@selector(compare:)];
        _countryArray = sortedCountryCodeArray;
        /*for (NSString *ccode in _countryArray) {
            NSLog(@"countryName=%@",ccode);
        };*/

        int countryCount = [_countryArray count];
        _countryBalances =  [NSMutableDictionary dictionaryWithCapacity:countryCount];
        
        //NSLog(@"number of country = %i", countryCount);//246 countries
        for (int t=0; t < countryCount; t++){
            
            balance = [[Balance alloc]init];
            balance.balanceDate = [NSDate date];
            
            NSString *countryCode = [_countryArray objectAtIndex:t];
            
                    
            aRand=0;
            bRand=0;
            cRand=0;
            dRand=0;
            eRand=0;
            balAmt=0;
            undueAmt=0;
            b1Amt=0;
            b2Amt=0;
            b3Amt=0;
            c1Amt=0;
            c2Amt=0;
            
            aRand = rand() % 200; //generate a random number
            bRand = rand() % 200; //generate a random number
            cRand = rand() % 200; //generate a random number
            dRand = rand() % 200; //generate a random number
            eRand = rand() % 200; //generate a random number
            //NSLog(@"a=%i,b=%i,c=%i,d=%i,e=%i",aRand,bRand,cRand,dRand,eRand);
            
            //overall balance
            //balAmt= 30000 + 50 *aRand; //all balances = undue+below90+above90 
            // 50 breaks down to  25 + (5+5+5) + 10 for undue, c1 and c2 respectively
            undueAmt = 10000 + 100 *aRand;
            b1Amt = 2000 + 25 *bRand; //bucket1: 1-30 days
            b2Amt = 1500 + 25 *cRand; //bucket2: 31-60 days
            b3Amt = 1000 + 25 *dRand; //bucket3: 61-90 days
            c1Amt = b1Amt + b2Amt + b3Amt;  //total of below90Days
            c2Amt = 2000 + 25 *eRand; //90+ days
            balAmt = undueAmt + c1Amt + c2Amt;
            
            //NSLog(@"balAmt=%i,undueAmt=%i,c1Amt=%i,c2Amt=%i",balAmt,undueAmt,c1Amt,c2Amt);
            
            balance.balanceAmount = [NSNumber numberWithInt:balAmt];
            balance.undueAmount = [NSNumber numberWithInt:undueAmt];
            balance.belowNinetyDaysAmount = [NSNumber numberWithInt:c1Amt];
            balance.bucketOneAmount = [NSNumber numberWithInt:b1Amt];
            balance.bucketTwoAmount = [NSNumber numberWithInt:b2Amt];
            balance.bucketThreeAmount = [NSNumber numberWithInt:b3Amt];
            balance.aboveNinetyDaysAmount = [NSNumber numberWithInt:c2Amt];
            balance.bucketFourAmount = [NSNumber numberWithInt:(0)];
            balance.bucketFiveAmount = [NSNumber numberWithInt:(0)];
            balance.bucketSixAmount = [NSNumber numberWithInt:(0)];
            balance.numberOfOpenInvoices = [NSNumber numberWithInt:bRand];
            
            [_countryBalances setObject:balance forKey: countryCode];
           
        };
     
    }
    return self;
}

/*
-(NSUInteger)getNumberOfDaysThisYearTillToday
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];  
    [df setDateFormat:@"MM-dd-yyyy"];  
    
    NSDate * newYearDay = [df dateFromString:@"01-01-2012"]; 
    NSDate * today = [[NSDate alloc]init];
    
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    
    //to get number of days since 01-01-2012
    NSDateComponents *components = [gregorian components:NSDayCalendarUnit
                                                fromDate:newYearDay
                                                  toDate:today options:0];
  
    NSInteger days = [components day];
    
    return days;
    //NSLog(@"days = %d", days);

}*/

-(NSUInteger)getNumberOfDaysFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [gregorian components:NSDayCalendarUnit
                                                fromDate:fromDate
                                                  toDate:toDate options:0];
    
    NSInteger days = [components day];
    
    return days;
       
}


@end
